package com.mini.demos.webgame.db;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.mini.demos.webgame.entity.User;

public class DBUtils {

	/**
	 * 添加.
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public int save(String sql, Object[] params) {
		int row = update(sql, params);
		return row;
	}

	/**
	 * 更新.
	 * 
	 * @param sql
	 * @param params
	 * @return 受影响的行数
	 */
	public int update(String sql, Object[] params) {
		QueryRunner queryRunner = new QueryRunner(DBPoolUtils.getdataSource());
		int affectedRows = 0;
		try {
			if (params == null) {
				affectedRows = queryRunner.update(sql);
			} else {
				affectedRows = queryRunner.update(sql, params);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return affectedRows;
	}

	/**
	 * 查询操作
	 * 
	 * @param sql
	 * @param param
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public List query(String sql, Class<?> clazz, Object... params) {
		try {
			QueryRunner qRunner = new QueryRunner(DBPoolUtils.getdataSource());
			List list = (List) qRunner.query(sql, new BeanListHandler(clazz),
					params);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String arg[]) {
		DBUtils test = new DBUtils();

		String sql1 = "update t_user set money = ? where loginName=?";
		Object[] params1 = new Object[] { Float.valueOf(0), "jason",};
		test.update(sql1, params1);

		String sql = "select * from t_user";
		Object[] params = new Object[] {  };
		List<User> list = test.query(sql, User.class,params);
		for (User user : list) {
			System.out.println(user.getLoginName()+":"+user.getMoney());
		}
	}

}
